<template>
  <div class="q-repository">
    <div class="q-repository-header">
      <h3>代码仓库列表</h3>
      <div>
        <el-button
          type="primary"
          size="small"
          @click="handleDialog('createDialog')"
        >创建代码仓库</el-button>
        <el-button
          type="primary"
          size="small"
          @click="handleDialog('importDialog')"
        >导入仓库</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <!-- <el-table
      v-loading="listLoading"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
      style="width: 100%">
      <el-table-column
        label="ID"
        prop="id">
      </el-table-column>
      <el-table-column
        label="仓库名"
        prop="name">
      </el-table-column>
      <el-table-column
        label="仓库简介"
        prop="description">
      </el-table-column>
      <el-table-column
        label="最后更新"
        prop="last_activity_at"
        :formatter="handleCreateTime"
      >
      </el-table-column>
      <el-table-column
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click.native="handleCode(scope.$index, scope.row)">仓库</el-button>
          <el-button
            size="mini"
            @click.native="editBranch(scope.$index, scope.row)">分支</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table> -->
    <q-table
      :data="tableData"
      :loading="listLoading"
      :columns="columns"
      :option="option"
      :pagination="pagination"
      @handle-operate="handleOperate"
    />
    <create-dialog ref="createDialog" :git-url="longPath" @update-list="fetchData" />
    <import-dialog ref="importDialog" :git-url="longPath" @update-list="fetchData" />
  </div>
</template>

<script>
import { getData, postData } from '@/api/requestData'
export default {
  components: {
    CreateDialog: () => import('../modals/create'),
    ImportDialog: () => import('../modals/import'),
    QTable: () => import('@/components/QTable')
  },
  data() {
    return {
      listLoading: true,
      tableData: [],
      longPath: '',
      search: '',
      dialogFormVisible: false,
      columns: [{
        prop: 'id',
        label: 'ID'
      }, {
        prop: 'name',
        label: '仓库名'
      }, {
        prop: 'description',
        label: '简介'
      }, {
        prop: 'last_activity_at',
        label: '最后更新',
        timeFormat: 'YYYY-MM-DD HH:mm:ss'
      }, {
        prop: 'operation',
        label: '操作',
        type: 'operation',
        commonStyle: {
          fontSize: '12px',
          borderRadius: '2px',
          padding: '2px 15px',
          marginRight: '12px',
          border: '1px solid #DCDFE6',
          cursor: 'pointer'
        },
        options: [{
          label: '仓库',
          value: 'repo',
          // style: {}
        }, {
          label: '分支',
          value: 'branch',
          // style: {}
        }, {
          label: '删除',
          value: 'delete',
          style: {
            backgroundColor: '#F56C6C',
            border: 'none',
            color: '#FFFFFF'
          }
        }]
      }],
      option: {
        height: 'calc(100% - 60px)',
      },
      pagination: {
        remote: false,
        currentPage: 1,
        total: 0,
        layout: 'total, sizes, prev, pager, next, jumper',
        pageSize: 15,
        pageSizes: [5, 10, 15, 20],
        hideOnSinglePage: true
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleDialog(name) {
      this.$refs[name].visibleChange()
    },
    fetchData() {
      this.listLoading = true
      // 获取仓库列表
      getData('git/list').then(response => {
        this.listLoading = false
        this.tableData = response.data.list
        this.$store.commit('code/CHANGE_REPOS', this.tableData)
        this.longPath = response.data.longPath
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleOperate(command, row) {
      switch (command) {
        // 仓库
        case 'repo':
          this.$router.push({ path: `/git/${row.id}/${row.name}/${row.default_branch || 'master'}/root`})
          break;
        // 分支
        case 'branch':
          this.$router.push({ path: `/code/branch/${row.id}`})
          break;
        // 删除
        case 'delete':
          this.handleDelete(row.id)
          break;
        default:
          break;
      }
    },
    handleDelete(id) {
      this.$confirm('确认删除此仓库?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonType: 'warning',
        cancelButtonType: 'text',
        type: 'warning'
      }).then(() => {
        // 确认处理逻辑
        postData('/git/del/repo', { id }).then(response => {
          this.fetchData()
          this.$message.success('删除成功')
        }).catch(() => {})
      })
    },
    resetTemp() {
      this.temp = {
        Name: '',
        Path: '',
        Description: '',
        Visibility: 'private',
        InitializeWithReadme: true,
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          postData('/git/create/repo',this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.fetchData()
          })
        }
      })
    },
    // 弹窗内方法
    editBranchName(evt, type) {
      const node = evt.target.closest('.branch-name')
      type === 'input' ? node.classList.remove('editable') : (node.classList.add('editable'), node.querySelector('input').focus())
    },
    addBranch(index) {
      this.$prompt('请输入分支名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if (this.branches.includes(value)) {
          this.$message({
            type: 'error',
            message: `${value}分支已存在`
          })
        } else {
          typeof index === 'undefined' ? this.branches.push(value) : this.branches.splice(index, 0, value)
        }
      }).catch(() => {});
    },
    removeBranch(index) {
      this.branches.splice(index, 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.q-repository {
  height: 100%;
  padding: 0 20px 20px;
  background-color: #FFF;
  &-header {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    h3 {
      margin-right: auto;
    }
  }
  .q-table {
    height: calc(100% - 50px);
  }
}
</style>
<style lang="scss">
.repository-dialog {
  .commit-flow {
    display: flex;
    align-items: center;
    margin-left: 50px;
    &-content {
      display: flex;
      align-items: center;
      margin-left: 12px;
      & > div {
        margin: 0 12px;
        display: flex;
        align-items: center;
        height: 32px;
        position: relative;
        .branch-name {
          padding: 0 6px;
          cursor: pointer;
          position: relative;
          .el-input {
            max-width: 120px;
            display: none;
          }
          &.editable {
            .branch-name-static {
              display: none;
            }
            .el-input {
              display: block;
            }
          }
          div {
            // position: absolute;
            // width: 100%;
            // height: 100%;
          }
        }
        span {
          display: inline-block;
          width: 20px;
          i {
            cursor: pointer;
            font-size: 16px;
            display: none;
          }
        }
        &:hover span i{
          display: inline-block;
        }
        &:not(:last-child):after {
          content: '\E6E9';
          font-family: element-icons!important;
          font-size: 18px;
          color: #333;
        }
      }
    }
  }
}
</style>